package com.zhixun.mobile.modules.site.web;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.boxin.ims.modules.momarketing.entity.CompanyNews;
import com.boxin.ims.modules.momarketing.entity.CustomPage;
import com.boxin.ims.modules.momarketing.entity.MicroPage;
import com.boxin.ims.modules.momarketing.entity.MicroProduct;
import com.boxin.ims.modules.momarketing.entity.PageTemplate;
import com.boxin.ims.modules.momarketing.entity.Project;
import com.boxin.ims.modules.momarketing.entity.ProjectMenu;
import com.boxin.ims.modules.momarketing.entity.ProjectVisit;
import com.boxin.ims.modules.momarketing.service.CompanyNewsService;
import com.boxin.ims.modules.momarketing.service.CustomPageService;
import com.boxin.ims.modules.momarketing.service.MicroPageService;
import com.boxin.ims.modules.momarketing.service.MicroProductService;
import com.boxin.ims.modules.momarketing.service.ProjectMenuService;
import com.boxin.ims.modules.momarketing.service.ProjectService;
import com.boxin.ims.modules.momarketing.service.ProjectVisitService;
import com.zhixun.mobile.common.utils.StringUtils;
import com.zhixun.mobile.modules.base.web.BaseController;
import com.zhixun.mobile.modules.site.statics.MicroPageUsage;
import com.zhixun.mobile.modules.site.statics.MicroSiteMenu;

/**  
* @author Administrator  
*    
*/
/**  
* @author Administrator  
*    
*/
@Controller
@RequestMapping(value= "/site")  /* site */
public class MicroSiteController extends BaseController {
	
	@Autowired
	private ProjectService projectService;
	
	@Autowired
	private MicroPageService microPageService;
	
	@Autowired
	private CustomPageService customPageService;
	
	@Autowired
	private ProjectVisitService projectVisitService;
	
	@Autowired
	private MicroProductService microProductService;
	
	@Autowired
	private CompanyNewsService companyNewsService;
	
	@Autowired
	private ProjectMenuService projectMenuService;
	
	@PersistenceContext
	private EntityManager entityManager;
	
	/**
	 * @author Jakemanse
	 * @time 2013-11-28  上午11:09:42
	 * @function <p> 微网站首页入口 </p>
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{proj_id}")
	public String viewSite(@PathVariable Long proj_id,HttpServletRequest request,HttpServletResponse response){
		/* 后台修改数据后发送该标示 */
//		String bg = request.getParameter("bg");
//		if(bg != null){
			/* 清除二级缓存 */
			EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
			/* 清除实体缓存 */
			entityManagerFactory.getCache().evict(Project.class);
			entityManagerFactory.getCache().evict(CompanyNews.class);
			entityManagerFactory.getCache().evict(MicroPage.class);
//		}
		
		/* 获取页面要展现的资源 */
		/* - 菜单展现公共项 */
		Project project = projectService.get(proj_id);
		/* -- 网站主题 */
		String theme = getProjectTheme(project);
		request.setAttribute("theme", theme);
		request.setAttribute("project", project);
		
		List<MicroPage> microPages= microPageService.findMicropagesByProjectId(proj_id);
		request.setAttribute("microPages", microPages);
		
		/* -- 检查网站是否失效 */
		if("1".equals(project.getDelFlag())){
			request.setAttribute("errorInfo", "您访问的页面已过期!");
			/* 返回地址待考虑 */
			return "modules/site/themes/"+theme+"/index";
		}
		
		/* menuId用于区分当前用户请求的列表内容；默认为1，即首页 */
		String menuId = request.getParameter("menuId");
		if(StringUtils.isEmpty(menuId)){
			menuId = "1";
			/* 首次不带menuId参数，被认为一条新访问记录 */
			/* 保存用户访问记录 */
			saveVisitRecord(menuId, proj_id, request);
		}
		
		/* 几个主题单独控制 */
//		if(theme.equals("XinWenLieBiao")){
//			switch (Integer.parseInt(menuId)) {
//			case 1:
//				List<MicroPage> pageList1 = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.INTERNAL);
//				request.setAttribute("internalPageList", pageList1);
//				List<MicroPage> pageList2 = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.INLAND);
//				request.setAttribute("inlandPageList", pageList2);
//				List<MicroPage> pageList3 = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.WAR);
//				request.setAttribute("warPageList", pageList3);
//				List<MicroPage> pageList4 = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.FUN);
//				request.setAttribute("funPageList", pageList4);
//				return "modules/site/themes/"+theme+"/index";
//			case 2:
//				List<MicroPage> pageList5 = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.INTERNAL);
//				request.setAttribute("internalPageList", pageList5);
//				return "modules/site/themes/"+theme+"/internal";
//			case 3:
//				List<MicroPage> pageList6 = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.INLAND);
//				request.setAttribute("inlandPageList", pageList6);
//				return "modules/site/themes/"+theme+"/inland";
//			case 4:
//				List<MicroPage> pageList7 = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.WAR);
//				request.setAttribute("warPageList", pageList7);
//				return "modules/site/themes/"+theme+"/war";
//			case 5:
//				List<MicroPage> pageList8 = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.FUN);
//				request.setAttribute("funPageList", pageList8);
//				return "modules/site/themes/"+theme+"/fun";
//			}
//		} else if(theme.equals("QiCheFuWu")){
//			switch (Integer.parseInt(menuId)) {
//			case 2:   	/* 预约试驾 */
//				return "modules/site/themes/"+theme+"/yuyueshijia";
//			case 3:		/* 预约保养 */
//				return "modules/site/themes/"+theme+"/yuyuebaoyang";
//			case 4:		/* 车主关怀 */
//				return "modules/site/themes/"+theme+"/chezhuguanhuai";
//			case 5:		/* 违章查询 */
//				return "modules/site/themes/"+theme+"/weizhangchaxun";
//			case 6:		/* 促销信息 */
//				List<MicroPage> pageList = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.PROMOTION);
//				request.setAttribute("pageList", pageList);
//				return "modules/site/themes/"+theme+"/cuxiaoxinxi";
//			case 7:		/* 车型展示 */
//				List<MicroProduct> productList = microProductService.findMicroProductsByProjectId(proj_id);
//				request.setAttribute("productList", productList);
//				return "modules/site/themes/"+theme+"/chexingzhanshi";
//			case 8:		/* 保险估算器 */
//				return "modules/site/themes/"+theme+"/baoxiangusuan";
//			case 9:		/* 贷款估算器 */
//				return "modules/site/themes/"+theme+"/daikuangusuan";
//			case 10:		/* 活动中心 */
//				List<MicroPage> pageList1 = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.ACTIVITY);
//				request.setAttribute("pageList", pageList1);
//				return "modules/site/themes/"+theme+"/huodongzhongxin";
//			case 11:	/* 新闻动态 */
//				List<MicroPage> pageList2 = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.NEWS);
//				request.setAttribute("pageList", pageList2);
//				return "modules/site/themes/"+theme+"/xinwendongtai";
//			case 12:	/* 品牌历程 */
//				List<MicroPage> pageList3 = microPageService.findMicropagesByUsage(proj_id, MicroPageUsage.BRAND);
//				request.setAttribute("pageList", pageList3);
//				return "modules/site/themes/"+theme+"/pinpailicheng";
//			case 13:	/* 联系我们 */
//				return "modules/site/themes/"+theme+"/lianxiwomen";
//			default:
//				return "modules/site/themes/"+theme+"/index";
//			}
//		}
		
		/* - 菜单区分网站内容 */
		String toPage = "index";
		ProjectMenu projectMenu = projectMenuService.get(Long.parseLong(menuId));
		String type = projectMenu.getType();
		if(type != null){
			if(MicroSiteMenu.INDEX.equals(type)){
				/* 首页 */
				/* 推荐产品 */
				List<MicroProduct> microProductList = microProductService.findIndexProductsByProjectId(proj_id);
				request.setAttribute("microProductList", microProductList);
				/* 公司动态 */
				List<CompanyNews> newsList = companyNewsService.findByProjectId(proj_id);
				request.setAttribute("newsList", newsList);
				
				toPage = "index";
			} else if(MicroSiteMenu.ABOUT.equals(type)){
				/* 关于我们 */
				
				toPage = "about";
			} else if(MicroSiteMenu.CONTACT.equals(type)){
				/* 联系我们 */
				
				toPage = "contact";
			} else if(MicroSiteMenu.LOTTERY.equals(type)){
				/* 在线抽奖 */
				
				toPage = "lottery";
			} else if(MicroSiteMenu.NEWS.equals(type)){
				/* 公司动态 */
				/* 公司动态 */
				List<CompanyNews> newsList = companyNewsService.findByProjectId(proj_id);
				request.setAttribute("newsList", newsList);
				toPage = "news";
			} else if(MicroSiteMenu.SURVEY.equals(type)){
				/* 在线调查 */
				toPage = "survey";
			} else if(MicroSiteMenu.PRODUCT.equals(type)){
				/* 微产品，上架产品 */
				List<MicroProduct> microProductList = microProductService.findIndexProductsByProjectId(proj_id);
				request.setAttribute("microProductList", microProductList);
				toPage = "productList";
			}
		}
		
		/* 初始化左侧菜单，包括当前菜单名称、所有菜单项、微网页航页 */
		initLayoutMenu(projectMenu.getName(), proj_id, request);
		
		System.out.println("theme:" + theme);
		
		
//		request.setAttribute("qrCode", qrCode);
		
		return "modules/site/themes/"+theme+"/"+toPage;
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-6-28  下午11:49:10
	 * @function <p> 产品明细 </p>
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "viewProduct/{id}")
	public String viewProduct(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response){
		
		MicroProduct microProduct = microProductService.get(id);
		System.out.println(microProduct.getName());
		System.out.println(id);
		/* 获取页面要展现的资源 */
		/* - 菜单展现公共项 */
		Project project = microProduct.getProject();
		/* -- 网站主题 */
		String theme = getProjectTheme(project);
		
		/* -- 检查网站是否失效 */
		if("1".equals(project.getDelFlag())){
			request.setAttribute("errorInfo", "您访问的页面已过期!");
			/* 返回地址待考虑 */
			return "modules/site/themes/"+theme+"/index";
		}
		
		/* 初始化左侧菜单，包括当前菜单名称、所有菜单项、微网页航页 */
		initLayoutMenu("产品", project.getId(), request);
		
		request.setAttribute("product", microProduct);
		request.setAttribute("theme", theme);
		request.setAttribute("project", project);
		
		return "modules/site/themes/"+theme+"/viewProduct";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-11-28  上午11:08:31
	 * @function <p> 查看微网站详细 </p>
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "viewPage/{id}")
	public String viewMricoPage(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response){
		MicroPage microPage = microPageService.get(id);
		
		/* 获取网站样式 */
		/* -- 网站主题 */
		Project project = microPage.getProject();
		
		String theme = getProjectTheme(project);

		request.setAttribute("project", project);

		/* 初始化左侧菜单，包括当前菜单名称、所有菜单项、微网页航页 */
		initLayoutMenu("公司动态", project.getId(), request);

		request.setAttribute("theme", theme);
		request.setAttribute("microPage", microPage);
		
		return "modules/site/themes/"+theme+"/viewMicroPage";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-11-27  上午12:37:33
	 * @function <p> 查看活动，新闻明细  </p>
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "viewNews/{id}")
	public String viewNews(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response){
		/* 清除二级缓存 */
		EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
		/* 清除实体缓存 */
		entityManagerFactory.getCache().evict(CompanyNews.class);
		CompanyNews news = companyNewsService.get(id);
		Project project = news.getProject();
		/* -- 网站主题 */
		String theme = getProjectTheme(project);
		
		request.setAttribute("news", news);
		request.setAttribute("project", project);

		/* 初始化左侧菜单，包括当前菜单名称、所有菜单项、微网页航页 */
		initLayoutMenu("公司动态", project.getId(), request);
		
		request.setAttribute("theme", theme);
		return "modules/site/themes/"+theme+"/viewNews";
	}

	/**
	  * @function 
	  * @author lzx
	  * @time 上午9:01:13
	  * @param proj_id
	  * @param request
	 */
	public void saveVisitRecord(String menuId, long proj_id, HttpServletRequest request){
		Project project = projectService.get(proj_id);
		String mobile = request.getParameter("mobile");
		String qq = request.getParameter("qq");
		
		ProjectVisit projectVisit = new ProjectVisit();
		projectVisit.setProject(project);
		projectVisit.setBrowser(request.getHeader("user-agent"));
		projectVisit.setIp(request.getRemoteHost());
		projectVisit.setMobile(mobile);
		projectVisit.setQq(qq);
		projectVisit.setMenuId(Long.parseLong(menuId));
		projectVisit.setCreateDate(new Date());
		
		projectVisitService.save(projectVisit);
	}
	
	/**  
	  * @function 
	  * @author lzx
	  * @time 2014-3-1 上午9:06:43
	  * @param proj_id  
	  */
	public String getProjectTheme(Project project){
		PageTemplate template = project.getPageTemplate();
		
		/* 获取主题样式 */
		String theme = template.getTheme();
		if(theme == null || "".equals(theme)){
			theme = "default";
		}
		return theme;
	}
	
	/**  
	  * @function 
	  * @author lzx
	  * @time 2014-3-1 上午9:19:10
	  * @param projectMenuMap
	  * @param proj_id
	  * @param request  
	  */
	public void initLayoutMenu(String menuName, long proj_id, HttpServletRequest request){
		/* 设置标题 */
		request.setAttribute("menuName", menuName);
		/* 所有Menu */
		List<ProjectMenu> projectMenus = projectMenuService.getAllDisplayMenus();
		/* 因为查出来的排序是降序的 这里反转一下 */
		Collections.reverse(projectMenus);
		request.setAttribute("menus", projectMenus);
		/* 自定义航页 */
		List<MicroPage> microPageList = microPageService.findMicropagesByProjectId(proj_id);
		request.setAttribute("microPageList", microPageList);
	}
	
	
	/**
	 * 自定义微网页
	 *@author xiaoqian
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * 2014-3-18下午1:27:04
	 */
	@RequestMapping(value = "viewMicroPageCustom/{id}")
	public String viewMicroPageCustom(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response){
		MicroPage microPage=microPageService.get(id);
		/* -- 网站主题 */
		EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
		/* 清除实体缓存 */
		entityManagerFactory.getCache().evict(MicroPage.class);
		request.setAttribute("microPage", microPage);
		
		return "modules/site/microPageCustom";
	}
	
	@RequestMapping(value = "toRichpage/{id}")
	public String viewRichCustomPage(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response){
		CustomPage page = customPageService.get(id);
		
		
		
		request.setAttribute("customPage", page);
		request.setAttribute("wechatId", request.getParameter("wechatId"));
		request.setAttribute("uid", request.getParameter("uid"));
		request.setAttribute("mobile", request.getParameter("mobile"));
		request.setAttribute("topage", request.getParameter("topage"));
		
		return "modules/site/richCustomPage";
	}
	
	
	
	
}

